//#include <stdio.h>
#include <iostream>

extern "C" { 
#include <jpeglib.h> 
} 

unsigned char * image_buffer;
int image_height;	
int image_width;	

void cvt_TestRead(FILE * filename)
{
	struct jpeg_decompress_struct cinfo;
	struct jpeg_error_mgr jerr;
	FILE *infile = filename;
	int row_stride;	
	unsigned char  *buffer;
	unsigned char *p;

	cinfo.err = jpeg_std_error(&jerr);
	jpeg_create_decompress(&cinfo);
	jpeg_stdio_src(&cinfo, infile);

	(void) jpeg_read_header(&cinfo, TRUE);

	(void) jpeg_start_decompress(&cinfo);

	row_stride = cinfo.output_width * cinfo.output_components;
	image_height = cinfo.output_height;
	image_width = cinfo.output_width;

	printf("Libjpeg image width = %d  height = %d , row_stride = %d \n",image_width,image_height,row_stride);

	buffer = (unsigned char *) malloc(row_stride);
	image_buffer = (unsigned char *) malloc(row_stride*cinfo.output_height);

	if( (buffer == NULL ) || (image_buffer == NULL) )
	{
		printf("Libjpeg malloc error \n");
	}
	else
	{
		printf("Libjpeg malloc ok \n");	

		p = image_buffer;
		while (cinfo.output_scanline < cinfo.output_height) 
		{
			(void) jpeg_read_scanlines(&cinfo, &buffer, 1);
			memcpy(p,buffer,row_stride);
			p += row_stride;
		}

		free(buffer);
	}

	(void) jpeg_finish_decompress(&cinfo);
	jpeg_destroy_decompress(&cinfo);
	fclose(infile);

	//FILE *outfile=fopen("out.bmp","wb");
	//if (outfile==NULL) 
	//{
	//	delete [] image_buffer;
	//	return;
	//}
	//fwrite(image_buffer,row_stride*cinfo.output_height,1,outfile);
	//fclose(outfile);
}

void cvt_TestWrite(FILE * filename, int quality)
{
	struct jpeg_compress_struct cinfo;
	struct jpeg_error_mgr jerr;
	FILE * outfile = filename;	
	JSAMPROW row_pointer[1];	
	int row_stride;	

	cinfo.err = jpeg_std_error(&jerr);
	jpeg_create_compress(&cinfo);

	jpeg_stdio_dest(&cinfo, outfile);
	cinfo.image_width = image_width; 
	cinfo.image_height = image_height;
	cinfo.input_components = 3;	
	cinfo.in_color_space = JCS_RGB; 
	jpeg_set_defaults(&cinfo);
	jpeg_set_quality(&cinfo, quality, true);
	jpeg_start_compress(&cinfo, TRUE);
	row_stride = image_width * 3;	

	while (cinfo.next_scanline < cinfo.image_height) 
	{
		row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
		(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
	}

	jpeg_finish_compress(&cinfo);
	jpeg_destroy_compress(&cinfo);
	int lll = cinfo.dest->free_in_buffer;
	//cinfo.
	fclose(outfile);
}

int main(int argc, char *argv[])
{
	FILE *infile;

	if ((infile = fopen("out.jpg", "rb")) == NULL) 
	{
		fprintf(stderr, "open %s failed!\n", argv[1]);
		return -1;
	}
	else
		fprintf(stderr, "open %s successed!\n", argv[1]);

	cvt_TestRead(infile);

	if(image_buffer != NULL)
	{
		if ((infile = fopen("in.jpg", "wb")) == NULL) 
		{
			return -1;
		}
		else
		{
			cvt_TestWrite(infile,70);
		}

		free(image_buffer);
	}

	return 0;
}
